package com.cloud.usercenter.controller;

import com.cloud.commonapi.jsonResult.Result;
import com.cloud.commonapi.model.User_info;
import com.cloud.usercenter.config.HttpUtils;
import com.cloud.usercenter.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * @author 陈楚城
 * @date 2019/9/27 15:25
 * 用户信息
 */
@RestController
@Api(description = "用户具体信息接口")
@RequestMapping("usercontroller/userinfo")
public class UserInfoController {
    @Autowired
    private UserService userService;

    @GetMapping("users")
    @ApiOperation(value = "查看登录人用户信息" ,notes = "未测试")
    public Result getuser( HttpSession session){
        Integer accountId = (Integer) session.getAttribute("loginId");
        User_info user_info=userService.getUser_infobyAccountid(accountId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("user_info",user_info);
        map.put("account",session.getAttribute("loginAccount"));
        if(map.size()>0){
            return Result.buildData(202,"查询成功",map);
        }
        return Result.build(400,"查询失败");
    }
    @GetMapping("users/{accountId}")
    @ApiOperation(value = "查看用户信息" ,notes = "未测试")
    public Result getuserinfo(@PathVariable Integer accountId, HttpSession session){
        User_info user_info=userService.getUser_infobyAccountid(accountId);

        if(user_info!=null){
            return Result.buildData(202,"查询成功",user_info);
        }
        return Result.build(400,"查询失败");
    }

    @PutMapping("users")
    @ApiOperation(value = "修改用户信息" ,notes = "未测试")
    public Result update(  User_info user_info, @RequestParam(value = "file", required = false) MultipartFile file, HttpSession session){
        if(file!=null) {
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "G:\\web\\html\\touxiang\\"; // 上传后的路径
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }

            user_info.setPicture("http://10.86.2.41:8090/touxiang/" + fileName);
        }
        user_info.setAccountId((Integer) session.getAttribute("loginId"));//登录人id
        if(userService.updateByAccountIdSelective(user_info) >0){
            return Result.build(200,"修改信息成功");
        }
        return Result.build(400,"修改信息失败");
    }

    @PutMapping("users/ByComment")
    @ApiOperation(value = "修改用户信息" ,notes = "未测试")
    public Result update1(  User_info user_info,  HttpSession session){

        if(userService.updateByAccountIdSelective(user_info) >0){
            return Result.build(200,"修改信息成功");
        }
        return Result.build(400,"修改信息失败");
    }

    @PostMapping("users/identity")
    @ApiOperation(value = "实名认证" ,notes = "未测试")
    public Result getIdentity(@RequestParam String realname,@RequestParam String identity,HttpSession session){
        String host = "https://idenauthen.market.alicloudapi.com";
        String path = "/idenAuthentication";
        String method = "POST";
        String appcode = "a76ea6447dc74ff2a2b238efd77039fc";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("idNo", identity);
        bodys.put("name", realname);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            //System.out.println(EntityUtils);
            String str=EntityUtils.toString(response.getEntity());
            System.out.println(str);
            if(str.contains("身份证信息匹配")||str.contains("信息匹配")){
                User_info user_info=new User_info();
                user_info.setAccountId((Integer) session.getAttribute("loginId"));//登录LoginID，session获取
                user_info.setRealname(realname);
                user_info.setIdcard(identity);
                user_info.setCredit(60);
                user_info.setLevel("合格");
                userService.updateByAccountIdSelective(user_info);
                return Result.build(200,"身份认证成功,已实名");
            }else
                return Result.build(400,"身份认证失败,请确认身份证号与姓名身份匹配");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }



}
